package com.cloudbroker.bcs.platform.dav.middle.extservice.yunxin.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.middle.extservice.yunxin.YunxinService;
import com.cloudbroker.bcs.platform.dav.common.util.CacheHelper;
import com.cloudbroker.bcs.platform.dav.common.util.CheckSumBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static java.lang.String.valueOf;

/**
 * Created by wangxu13798 on 2016/3/14.
 */
@SuppressWarnings("deprecation")
@Service
public class YunxinServiceImpl implements YunxinService {

    private static Logger logger = LoggerFactory.getLogger(YunxinServiceImpl.class);

    @Override
    public Map<String, Object> general(Map<String, Object> params, String url) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String value = ValueUtil.getString(entry.getValue());
                    if (value != null && !"".equals(value)) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            String curTime = valueOf((new Date()).getTime() / 1000L);
            String checkSum = CheckSumBuilder.getCheckSum(ConfigValues.getYunxinAppSecret(),
                    ConfigValues.getYunxinNonce(), curTime);// 参考 计算CheckSum的java代码
            // 设置请求的header
            httpPost.addHeader("AppKey", ConfigValues.getYunxinAppkey());
            httpPost.addHeader("Nonce", ConfigValues.getYunxinNonce());
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 设置请求的参数
            if (pairs != null && !pairs.isEmpty()) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, "utf-8"));
            }
            
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            logger.info("\r\n"+new Date().toString()+"--");
            logger.info(result +"\r\n");
            // 打印执行结果
            return JSONObject.parseObject(result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e2) {
                
            }
        }
        return null;
    }
    
    /**
     * 创建云信ID
     * @param params y-{accid} n-{name,props,icon,token}
     * @return 用户id和token
     */
    
    @Override
    public Map<String, Object> accountCreate(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/create.action";
        return general(params, url);
    }
    
    /**
     * 云信ID更新
     * @param params y-{accid} n-{props,token}
     * @return code,200-成功
     */
    
    @Override
    public Map<String, Object> accountUpdate(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/update.action";
        return general(params, url);
    }
    
    /**
     * 更新并获取新token
     * @param params y-{accid}
     * @return code,200-成功 info={accid="",token=""}
     */
    
    @Override
    public Map<String, Object> refreshToken(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/refreshToken.action";
        return general(params, url);
    }
    
    /**
     * 封禁云信ID
     * @param params y-{accid}
     * @return code,200-成功
     */
    
    @Override
    public Map<String, Object> accountBlock(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/block.action";
        return general(params, url);
    }
    
    /**
     * 解禁云信ID
     * @param params y-{accid}
     * @return code,200-成功
     */
    
    @Override
    public Map<String, Object> accountUnBlock(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/unblock.action";
        return general(params, url);
    }
    
    /**
     * 更新用户名片
     * @param params y-{accid} n-{name,icon,sign,email,birth,mobile,gender,ex}
     * @return code,200-成功
     */
    
    @Override
    public Map<String, Object> updateUserInfo(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/updateUinfo.action";
        return general(params, url);
    }
    
    /**
     * 获取用户名片
     * @param params y-{accids} accids为json数组，格式为accids=['accid1','accid2'---]
     * @return code,200-成功 , uinfos={email="",accid="",name="",gender="",mobile=""}
     */
    
    @Override
    public Map<String, Object> getUserInfo(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/getUinfos.action";
        return general(params, url);
    }
    
    /**
     * 创建聊天室
     * @param params y-{creator,name} n-{announcement,broadcasturl,ext}
     * @return code,200-成功 , chatroot={roomid,valid,announcement,name,broadcasturl,ext,creator}
     */
    
    @Override
    public Map<String, Object> createChatroom(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/create.action";
        return general(params, url);
    }
    
    /**
     * 查询聊天室信息
     * @param params y-{roomid} n={needOnlineUserCount}
     * @return code,200-成功 , chatroot={roomid,valid,announcement,name,broadcasturl,ext,creator}
     */
    
    @Override
    public Map<String, Object> getChatroomInfo(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/get.action";
        return general(params, url);
    }
    
    /**
     * 更新聊天室信息
     * @param params y-{roomid} n-{name,announcement,broadcasturl,ext,needNotify,notifyExt}
     * @return code,200-成功 , chatroot={roomid,valid,announcement,name,broadcasturl,ext,creator}
     */
    
    @Override
    public Map<String, Object> updateChatroomInfo(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/update.action";
        return general(params, url);
    }
    
    /**
     * 修改聊天室开/关闭状态
     * @param params y-{roomid,operator,avlid}
     * @return roomid,valid,announcement,name,broadcasturl,ext,creator
     */
    
    @Override
    public Map<String, Object> toggleCloseStat(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/toggleCloseStat.action";
        return general(params, url);
    }
    
    /**
     * 设置聊天室内用户角色
     * @param params y-{roomid,operator,target,opt,optvalue}
     * @return roomid,level,accid,type
     */
    
    @Override
    public Map<String, Object> setMemberRole(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/setMemberRole.action";
        return general(params, url);
    }
    
    /**
     * 请求聊天室地址
     * @param params y-{roomid,accid} n-{clienttype}
     * @return code 200-成功 ,addr=["addr1","addr2"] addr为json数组
     */
    
    @Override
    public Map<String, Object> getChatroomAddr(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/requestAddr.action";
        return general(params, url);
    }
    
    /**
     * 发送聊天室消息
     * @param params y-{roomid,msgId,fromAccid,msgType} n-{resendFlag,attach,ext}
     * @return code 200-成功
     *         ,desc={time,fromAvator,msgid_client,fromClientType,attach,roomId,fromAccount,fromNick,type,ext}
     */
    
    @Override
    public Map<String, Object> sendChatroomMsg(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/chatroom/sendMsg.action";
        return general(params, url);
    }
    
    /**
     * P2P拉黑或静音
     * @param params y-{accid,targetAcc,relationType,value}
     * @return code 200-成功
     */
    
    @Override
    public Map<String, Object> setSpecialRelation(Map<String, Object> params) {
        String url = "https://api.netease.im/nimserver/user/setSpecialRelation.action";
        return general(params, url);
    }

    @Override
    public Map<String, Object> setHisChat(String broker_key,String content) {
        CacheHelper.zadd(broker_key,new Date().getTime(),content);
        if (CacheHelper.ttl(broker_key) == -1){
            CacheHelper.expire(broker_key, getTimesnight()-(int) (System.currentTimeMillis()/1000));
        }
        return VOUtil.genSuccessResult();
    }

    @Override
    public Map<String, Object> getHisChat(String broker_key,Long position,Long num){
        Map<String,Object> map = new HashMap<>();
        if (position == 0){
            map.put("content","");
            map.put("position",0);
        }else {
            Set<String> contentSet = position > num ? CacheHelper.zrange(broker_key,position-num,position-1)
                    : CacheHelper.zrange(broker_key,0,position-1);
            map.put("content",contentSet);
            map.put("position",position - num > 0 ? position-num : 0);
        }
        return VOUtil.setSuccessResult(map);
    }

    public static int getTimesnight(){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (int) (cal.getTimeInMillis()/1000);
    }
}
